import {getToken, setToken, removeToken, saveUserInfo, loadUserinfo, removeUserInfo} from '@/utils/storage.js'
import {http} from "@/api";


// 重置用户令牌和角色信息
const state = {
    userInfo: loadUserinfo() || {},
    token: getToken(),
}

const mutations = {
    SET_USERINFO: (state, data) => {
        saveUserInfo(data)
        state.userInfo = data
    },
    SET_TOKEN: (state, token) => {
        setToken(token)
        state.token = token
    },
    LOGOUT(state) {
        removeToken();
        removeUserInfo()
        state.userInfo = {};
        state.token = '';
    },
};

const actions = {
    getUserInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            http.user.getUserInfo(state.userInfo.id).then(res => {
                commit('SET_USERINFO', res.data);
                resolve(res.data)
            }).catch(() => {
                reject()
            })
        })
    },
    updateProfile({ commit, state }, data) {
        return new Promise((resolve, reject) => {
            http.user.update(state.userInfo.id, data).then(res => {
                commit('SET_USERINFO', res.data);
                resolve()
            }).catch(() => {
                reject()
            })
        })
    },
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('LOGOUT')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
